<template>
  <div class="admin-users-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
      <p class="page-subtitle">管理系统中的所有用户账号</p>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-filters">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名、ID或手机号"
          prefix-icon="Search"
          class="search-input"
          @keyup.enter="searchUsers"
        />
        <el-select v-model="userStatus" placeholder="用户状态" class="status-select">
          <el-option label="全部" value="" />
          <el-option label="正常" value="active" />
          <el-option label="禁用" value="disabled" />
          <el-option label="待审核" value="pending" />
        </el-select>
        <el-select v-model="userRole" placeholder="用户角色" class="role-select">
          <el-option label="全部" value="" />
          <el-option label="普通用户" value="user" />
          <el-option label="管理员" value="admin" />
          <el-option label="版主" value="moderator" />
        </el-select>
        <el-button type="primary" @click="searchUsers">搜索</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <el-button type="primary" @click="batchImport">批量导入</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalUsers }}</span>
          <span class="stat-label">总用户数</span>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ activeUsers }}</span>
          <span class="stat-label">活跃用户</span>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ disabledUsers }}</span>
          <span class="stat-label">禁用用户</span>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ pendingUsers }}</span>
          <span class="stat-label">待审核用户</span>
        </div>
      </el-card>
    </div>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-card>
        <el-table :data="usersData" style="width: 100%" v-loading="isLoading">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="userId" label="用户ID" width="120" />
          <el-table-column prop="nickname" label="用户名" width="150" />
          <el-table-column prop="phone" label="手机号" width="150" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="role" label="角色" width="100">
            <template #default="scope">
              <el-tag :type="getRoleTagType(scope.row.role)">
                {{ getRoleLabel(scope.row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="registrationTime" label="注册时间" width="180" />
          <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="text" size="small" @click="viewUserDetail(scope.row)">详情</el-button>
              <el-button type="text" size="small" :class="scope.row.status === 'active' ? 'text-danger' : 'text-success'" @click="toggleUserStatus(scope.row)">
                {{ scope.row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button type="text" size="small" @click="editUserRole(scope.row)">修改角色</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalUsers"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加用户模态框 -->
    <el-dialog v-model="showAddUserModal" title="添加用户" width="600px" append-to-body>
      <div class="form-container">
        <el-form :model="newUserForm" :rules="newUserRules" ref="newUserFormRef" label-width="100px">
          <el-form-item label="用户名" prop="nickname">
            <el-input v-model="newUserForm.nickname" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="newUserForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="newUserForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="newUserForm.role" placeholder="请选择角色">
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
              <el-option label="版主" value="moderator" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="newUserForm.status" placeholder="请选择状态">
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showAddUserModal = false">取消</el-button>
        <el-button type="primary" @click="confirmAddUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 用户详情模态框 -->
    <el-dialog v-model="showUserDetailModal" :title="userDetailTitle" width="800px" append-to-body>
      <div v-if="selectedUser" class="user-detail">
        <div class="detail-header">
          <el-avatar :size="80" class="detail-avatar">
            <img v-if="selectedUser.avatarUrl" :src="selectedUser.avatarUrl" alt="用户头像" />
            <span v-else>{{ selectedUser.nickname.charAt(0).toUpperCase() }}</span>
          </el-avatar>
          <div class="detail-info">
            <h3 class="detail-name">{{ selectedUser.nickname }}</h3>
            <p class="detail-id">ID: {{ selectedUser.userId }}</p>
          </div>
          <div class="detail-actions">
            <el-button 
              type="default" 
              size="small" 
              :class="selectedUser.status === 'active' ? 'text-danger' : 'text-success'"
              @click="toggleUserStatus(selectedUser)"
            >
              {{ selectedUser.status === 'active' ? '禁用账号' : '启用账号' }}
            </el-button>
            <el-button type="default" size="small" @click="editUserRole">修改角色</el-button>
            <el-button type="danger" size="small" @click="deleteUser">删除账号</el-button>
          </div>
        </div>
        <div class="detail-content">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-item">
              <span class="detail-label">手机号：</span>
              <span class="detail-value">{{ selectedUser.phone || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">邮箱：</span>
              <span class="detail-value">{{ selectedUser.email || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">角色：</span>
              <span class="detail-value">{{ getRoleLabel(selectedUser.role) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">状态：</span>
              <span class="detail-value">{{ getStatusLabel(selectedUser.status) }}</span>
            </div>
          </div>
          <div class="detail-section">
            <h4>活动信息</h4>
            <div class="detail-item">
              <span class="detail-label">注册时间：</span>
              <span class="detail-value">{{ selectedUser.registrationTime || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">最后登录：</span>
              <span class="detail-value">{{ selectedUser.lastLoginTime || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">发帖数：</span>
              <span class="detail-value">{{ selectedUser.postCount || 0 }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">评论数：</span>
              <span class="detail-value">{{ selectedUser.commentCount || 0 }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showUserDetailModal = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 搜索和筛选条件
const searchKeyword = ref('');
const userStatus = ref('');
const userRole = ref('');

// 加载状态
const isLoading = ref(false);

// 模态框控制
const showAddUserModal = ref(false);
const showUserDetailModal = ref(false);

// 选择的用户
const selectedUser = ref<any>(null);
const userDetailTitle = computed(() => {
  return selectedUser.value ? `用户详情 - ${selectedUser.value.nickname}` : '用户详情';
});

// 统计数据
const totalUsers = ref(1286);
const activeUsers = ref(958);
const disabledUsers = ref(156);
const pendingUsers = ref(172);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(20);

// 用户数据
const usersData = ref<any[]>([
  // 模拟数据
  {
    userId: '10001',
    nickname: 'admin',
    phone: '13800138000',
    email: 'admin@example.com',
    role: 'admin',
    status: 'active',
    registrationTime: '2023-01-15 10:30:00',
    lastLoginTime: '2024-05-10 09:15:00'
  },
  {
    userId: '10002',
    nickname: 'user1',
    phone: '13800138001',
    email: 'user1@example.com',
    role: 'user',
    status: 'active',
    registrationTime: '2023-02-20 14:20:00',
    lastLoginTime: '2024-05-09 16:45:00'
  },
  {
    userId: '10003',
    nickname: 'user2',
    phone: '13800138002',
    email: 'user2@example.com',
    role: 'user',
    status: 'disabled',
    registrationTime: '2023-03-05 09:45:00',
    lastLoginTime: '2024-04-20 11:30:00'
  },
  {
    userId: '10004',
    nickname: 'moderator1',
    phone: '13800138003',
    email: 'moderator1@example.com',
    role: 'moderator',
    status: 'active',
    registrationTime: '2023-01-25 16:10:00',
    lastLoginTime: '2024-05-10 10:20:00'
  },
  {
    userId: '10005',
    nickname: 'user3',
    phone: '13800138004',
    email: 'user3@example.com',
    role: 'user',
    status: 'active',
    registrationTime: '2023-04-10 11:25:00',
    lastLoginTime: '2024-05-08 15:10:00'
  }
]);

// 添加用户表单
const newUserForm = reactive({
  nickname: '',
  phone: '',
  email: '',
  role: 'user',
  status: 'active'
});

const newUserFormRef = ref<any>(null);

// 添加用户表单规则
const newUserRules = {
  nickname: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 获取角色标签类型
const getRoleTagType = (role: string) => {
  switch (role) {
    case 'admin':
      return 'primary';
    case 'moderator':
      return 'success';
    case 'user':
    default:
      return 'info';
  }
};

// 获取角色标签
const getRoleLabel = (role: string) => {
  switch (role) {
    case 'admin':
      return '管理员';
    case 'moderator':
      return '版主';
    case 'user':
    default:
      return '普通用户';
  }
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case 'active':
      return 'success';
    case 'disabled':
      return 'danger';
    case 'pending':
      return 'warning';
    default:
      return 'info';
  }
};

// 获取状态标签
const getStatusLabel = (status: string) => {
  switch (status) {
    case 'active':
      return '正常';
    case 'disabled':
      return '禁用';
    case 'pending':
      return '待审核';
    default:
      return '未知';
  }
};

// 搜索用户
const searchUsers = () => {
  isLoading.value = true;
  // 模拟搜索请求
  setTimeout(() => {
    // 这里应该是实际的搜索逻辑
    ElMessage.success('搜索成功');
    isLoading.value = false;
  }, 800);
};

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = '';
  userStatus.value = '';
  userRole.value = '';
  currentPage.value = 1;
  searchUsers();
};

// 查看用户详情
const viewUserDetail = (user: any) => {
  selectedUser.value = { ...user };
  showUserDetailModal.value = true;
};

// 切换用户状态
const toggleUserStatus = (user: any) => {
  const newStatus = user.status === 'active' ? 'disabled' : 'active';
  
  ElMessageBox.confirm(
    `确定要${newStatus === 'disabled' ? '禁用' : '启用'}用户"${user.nickname}"吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里应该是实际的API调用逻辑
    user.status = newStatus;
    ElMessage.success(`用户"${user.nickname}"已${newStatus === 'disabled' ? '禁用' : '启用'}`);
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 编辑用户角色
const editUserRole = (user?: any) => {
  const targetUser = user || selectedUser.value;
  if (!targetUser) return;
  
  ElMessageBox.confirm(
    `确定将用户"${targetUser.nickname}"的角色修改为`,
    '修改角色',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
      distinguishCancelAndClose: true
    }
  ).then(() => {
    // 这里应该先显示一个角色选择的界面，然后再执行修改操作
    // 为了简化，我们暂时直接修改为管理员角色
    const newRole = 'admin'; // 这里应该是实际的角色选择
    if (newRole !== targetUser.role) {
      // 这里应该是实际的API调用逻辑
      targetUser.role = newRole;
      ElMessage.success(`用户"${targetUser.nickname}"的角色已修改为${getRoleLabel(newRole)}`);
    }
  }).catch(() => {
    ElMessage.info('已取消修改');
  });
};

// 删除用户
const deleteUser = () => {
  if (!selectedUser.value) return;
  
  ElMessageBox.confirm(
    `确定要删除用户"${selectedUser.value.nickname}"吗？此操作不可撤销！`,
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    // 这里应该是实际的API调用逻辑
    const index = usersData.value.findIndex(u => u.userId === selectedUser.value.userId);
    if (index !== -1) {
      usersData.value.splice(index, 1);
      totalUsers.value--;
      showUserDetailModal.value = false;
      ElMessage.success(`用户"${selectedUser.value.nickname}"已删除`);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 添加用户
const addUser = () => {
  showAddUserModal.value = true;
};

// 确认添加用户
const confirmAddUser = () => {
  if (newUserFormRef.value) {
    newUserFormRef.value.validate((valid: boolean) => {
      if (valid) {
        // 这里应该是实际的API调用逻辑
        const newUser = {
          userId: `1${Date.now()}`,
          ...newUserForm,
          registrationTime: new Date().toLocaleString('zh-CN'),
          lastLoginTime: new Date().toLocaleString('zh-CN')
        };
        usersData.value.unshift(newUser);
        totalUsers.value++;
        if (newUser.status === 'active') activeUsers.value++;
        else if (newUser.status === 'disabled') disabledUsers.value++;
        
        showAddUserModal.value = false;
        // 重置表单
        Object.keys(newUserForm).forEach(key => {
          if (key === 'role') (newUserForm as any)[key] = 'user';
          else if (key === 'status') (newUserForm as any)[key] = 'active';
          else (newUserForm as any)[key] = '';
        });
        
        ElMessage.success('用户添加成功');
      }
    });
  }
};

// 批量导入
const batchImport = () => {
  ElMessage.info('批量导入功能开发中...');
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  searchUsers();
};

const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  searchUsers();
};

// 生命周期钩子
onMounted(() => {
  searchUsers();
});
</script>

<style lang="scss" scoped>
@use "@/styles/variables.scss" as *;

.admin-users-view {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: $text-primary;
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: $text-secondary;
  margin: 5px 0 0 0;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-filters {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.status-select,
.role-select {
  width: 150px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.statistics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: $primary-color;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: $text-secondary;
  margin-top: 5px;
}

.table-container {
  margin-bottom: 30px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-container {
  max-height: 400px;
  overflow-y: auto;
}

.user-detail {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 20px;
  border-bottom: 1px solid $border-color;
  margin-bottom: 20px;
}

.detail-avatar {
  margin-right: 20px;
}

.detail-info h3 {
  margin: 0 0 5px 0;
  font-size: 20px;
  color: $text-primary;
}

.detail-info p {
  margin: 0;
  font-size: 14px;
  color: $text-secondary;
}

.detail-actions {
  display: flex;
  gap: 10px;
}

.detail-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.detail-section h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: $text-primary;
  font-weight: 600;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-label {
  font-size: 14px;
  color: $text-secondary;
  width: 100px;
  flex-shrink: 0;
}

.detail-value {
  font-size: 14px;
  color: $text-primary;
  flex: 1;
}

// 响应式设计
@media (max-width: 1200px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-filters {
    justify-content: center;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .detail-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .admin-users-view {
    padding: 10px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .status-select,
  .role-select {
    width: 100%;
  }
  
  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .detail-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .stat-card {
    padding: 15px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}
</style>